/**
 * 面谈总结/面谈详情
 */
import React, { useMemo } from 'react';
import { withRouter } from 'umi';
import { Form, Spin, message, Modal, Button } from 'antd';
import { debounce } from 'lodash';

import { useRequest, defaultFormatResult } from '@/hooks';
import { PageContainer } from '@/molecules';
import pageTabUtil from '@/utils/pageTabUtil';

import { TitleControl } from '@/pages/Recruitment/components';
import { ProfileCard } from '@/containers';
import { BottomAction } from '@/components';
import { useBeforeConclusion } from '../hooks';
import { TalkResult, TalkQuestionResult, TalkIM, TalkConclusionForm, TalkArrange } from '../containers';
import {
    getConclusion,
    submitConclusion,
    createImGroup,
    getConclusionSubmitStatus
} from '../../service';

const Detail = ({ location, form }) => {
    const { query, pathname } = location;
    const { interviewRefCode = '', arrangeId = '', employeeCode = '' } = query;
    const isConclusion = useMemo(() => pathname.includes('conclusion'), [query]);
    const { tabModalContent } = useBeforeConclusion(arrangeId, isConclusion);
    const [pageLoading, setPageLoading] = React.useState(false);
    const [changeQueryStatus, setChangeQueryStatus] = React.useState(true);

    const { data: conclusionData = {}, loading: conclusionLoading, run: runConclusion } = useRequest(
        () => getConclusion(arrangeId, interviewRefCode),
        {
            manual: isConclusion && changeQueryStatus,
            ...defaultFormatResult
        }
    );

    const { loading: imLoading } = useRequest(
        () =>
            createImGroup({
                arrangeId
            }),
        {
            ready: isConclusion,
            ...defaultFormatResult,
            onSuccess() {
                setChangeQueryStatus(false);
                runConclusion();
            }
        }
    );


    const onSubmitConclusion = async values => {
        try {
            const { hasAgree, summary } = values;
            const res = await submitConclusion({
                arrangeId,
                dimissionCode: interviewRefCode,
                hasAgree: !!hasAgree,
                summary
            });
            if (res.code === 10000) {
                pageTabUtil.goBack();
            } else {
                message.error(res.msg);
            }
        } catch (e) {
            console.log(e);
        }
    };
    const onInterviewSubmit = debounce(() => {
        form.validateFields(async (err, values) => {
            if (!err) {
                try {
                    setPageLoading(true);
                    const { code, data } = await getConclusionSubmitStatus(arrangeId);
                    setPageLoading(false);
                    if (code === 10000) {
                        if (data) {
                            onSubmitConclusion(values);
                            return;
                        }
                        Modal.confirm({
                            title: '提示',
                            content: '还有面谈官未提交面谈记录，是否发起面谈总结？',
                            onOk: async () => {
                                onSubmitConclusion(values);
                            }
                        });
                    }
                } catch (e) {
                    setPageLoading(false);
                }
            }
        });
    }, 400);
    const conclusionStatus = useMemo(() => !(conclusionData?.interviewArrangeVO?.interviewStatus === '5'),
        [conclusionData]);
    return (
        <PageContainer>
            <Spin spinning={pageLoading}>
                <Spin spinning={conclusionLoading || imLoading}>
                    <ProfileCard employeeCode={employeeCode}/>
                    <TitleControl title="面谈安排">
                        <TalkArrange
                            data={conclusionData?.interviewArrangeVO}
                            dimissionInfo={conclusionData?.dimissionOrderVO}
                        />
                    </TitleControl>
                    {
                        isConclusion && conclusionStatus && <TitleControl title="面谈总结">
                            <TalkConclusionForm
                                loading={pageLoading || conclusionLoading || imLoading}
                                form={form}
                                style={{ width: '460px', marginTop: 16 }}
                            />
                        </TitleControl>
                    }
                    {
                        isConclusion && conclusionStatus && <TitleControl title="面谈讨论" initialActive={false}>
                            <TalkIM
                                data={conclusionData}
                                isConclusion={isConclusion}
                                arrangeId={arrangeId}
                                conclusionImTip="已发起 IM 讨论，系统自动为为面谈参与人发起讨论群"
                            />
                        </TitleControl>
                    }
                    <TitleControl title={conclusionStatus ? '面谈建议' : '面谈结果'}>
                        <TalkResult data={conclusionData} conclusionStatus={conclusionStatus}/>
                    </TitleControl>
                    <TitleControl title="面谈问题">
                        <TalkQuestionResult data={conclusionData}/>
                    </TitleControl>
                    {
                        (!isConclusion || !conclusionStatus) && conclusionData?.interviewArrangeVO?.imGroupId && <TitleControl title="总结记录">
                            <TalkIM
                                data={conclusionData}
                                isConclusion={isConclusion}
                                arrangeId={arrangeId}
                                conclusionImTip="已发起 IM 讨论，系统自动为面谈参与人发起讨论群"
                            />
                        </TitleControl>
                    }
                </Spin>
                {tabModalContent}
                {
                    isConclusion && conclusionStatus && <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()} style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button type="primary" onClick={onInterviewSubmit} loading={pageLoading || conclusionLoading || imLoading}>
                            提交
                        </Button>
                    </BottomAction>
                }
            </Spin>
        </PageContainer>
    );
};

export default Form.create()(withRouter(Detail));
